var express = require('express');
var mysql = require('mysql');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//链接数据库
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '9527',
    database: 'myproject'
});
connection.connect();
//设置跨域
var allowCors = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Credentials','true');
  next();
};
app.use(allowCors);
//查询
app.get('/query', function (req, res) {
    var sql = 'select * from timeRecord';
    connection.query(sql, function (err, result) {
        if (err) {
            console.log('err:', err.message);
        }
        res.status(200),
            res.json({
                data: result,
                code: '000',
                message: '成功',
                status:200
            });
    });
});    
    //修改
    app.get('/change', function (req, res) {
        var id = req.query.id;
        var endTime = req.query.endTime;
        var sql = `update timeRecord set endTime = '${endTime}' where id = '${id}'`;
        connection.query(sql, function (err, result) {
            if (err) {
                console.log('err:', err.message);
            }
            res.status(200),
            res.json("修改成功")
        });
    })
    //添加
    app.get('/add', function (req, res) {
        var DATE = req.query.date;
        var realdate = req.query.realdata
        var sql = `insert into timeRecord(createTime,startTime,realTime) values ('${DATE}','${DATE}','${realdate}')`;
        connection.query(sql, function (err, result) {
            if (err) {
                console.log('err:', err.message);
            }
            res.status(200),
            res.json("添加成功")
        });
    })
    //删除
    app.get('/delete', function (req, res) {
        var ID = req.query.id;
        var sql = `delete from timeRecord where id='${ID}'`;
        connection.query(sql, function (err, result) {
            if (err) {
                console.log('err:', err.message);
            }
            res.status(200),
                res.json("删除成功")
        });
    })

    //connection.end();

    //配置服务端口
    var server = app.listen(3000, function () {
        var host = server.address().address;
        var port = server.address().port;
        console.log('服务器开启成功', port)
    })


